<template>
  <div class="role">
    <PageSearch :formConfig="formConfig" />
    <PageContent
      :tableConfig="tableConfig"
      pageName="role"
      @newPageData="newPageData"
      @editPageData="editPageData"
    />
    <PageDialog
      :dialogConfig="dialogConfig"
      ref="pageDialogRef"
      pageName="role"
      :defaultInfo="defaultInfo"
      :otherInfo="otherInfo"
    >
      <el-tree
        ref="treeRef"
        :props="{ children: 'children', label: 'name' }"
        show-checkbox
        node-key="id"
        :data="menus"
        class="menu-tree"
        @check="checkChange"
      ></el-tree>
    </PageDialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, computed, ref, nextTick } from 'vue'
import { useStore } from '@/store'
import { mapMenuToLeaf } from '@/utils/map-menu'
import type { ElTree } from 'element-plus'

import PageSearch from '@/components/page-search'
import PageContent from '@/components/page-content'
import PageDialog from '@/components/page-dialog'

import { useFormConfig } from './config/configForm'
import { useTableConfig } from './config/configTable'
import { useDialogConfig } from './config/configDialog'

import { usePageDialog } from '@/hooks/use-page-dialog'

const formConfig = reactive(useFormConfig())
const tableConfig = reactive(useTableConfig())
const dialogConfig = reactive(useDialogConfig())

// 处理编辑时树组件权限勾选的回显
const treeRef = ref<InstanceType<typeof ElTree>>()
const editCb = (item: any) => {
  const leafKeys = mapMenuToLeaf(item.menuList)
  nextTick(() => {
    // console.log(treeRef.value)
    treeRef.value?.setCheckedKeys(leafKeys, false)
  })
}

const [defaultInfo, pageDialogRef, newPageData, editPageData] = usePageDialog(
  undefined,
  editCb
)

const store = useStore()
const menus = computed(() => store.state.entireMenus)

const otherInfo = ref({})
const checkChange = (data1: any, data2: any) => {
  const checkedKeys = data2.checkedKeys
  const halfCheckedKeys = data2.halfCheckedKeys
  const menuList = [...checkedKeys, ...halfCheckedKeys]
  otherInfo.value = { menuList }
}
</script>

<style scoped lang="less">
.menu-tree {
  margin-left: 35px;
}
</style>
